import type { Ref } from 'vue'
import type { Teacher } from './useClassManagement'
import { ref } from 'vue'
import message from '@/components/common/message'
import { addTeacherToClass, deleteTeacherFromClass } from '@/request/class'
import { leaveClass } from '@/request/teacher/class'
import { useTeacherStore } from '@/store/teacher'

export function useTeacherManagement(classId: Ref<string>, teachers: Ref<Teacher[]>) {
  const newTeacher = ref({ name: '', phone: '' })
  const isAddingTeacher = ref(false)

  // 添加教师
  async function handleAddTeacher() {
    if (!newTeacher.value.name || !newTeacher.value.phone) {
      message.error('请填写教师姓名和手机号')
      return
    }

    if (!classId.value) {
      message.error('请先保存班级信息')
      return
    }

    try {
      await addTeacherToClass({
        cid: classId.value,
        teacher: {
          name: newTeacher.value.name,
          phone: newTeacher.value.phone,
        },
      })

      teachers.value.push({
        ...newTeacher.value,
        gender: '',
      })
      newTeacher.value = { name: '', phone: '' }
      isAddingTeacher.value = false
      message.success('教师添加成功')
    }
    catch (error) {
      console.error('添加教师失败:', error)
      message.error('添加教师失败')
    }
  }

  // 删除教师
  async function handleRemoveTeacher(teacher: Teacher) {
    if (!classId.value)
      return
    try {
      const self = useTeacherStore()
      if (teacher.tid === self.teacher.teacherId) {
        await leaveClass({
          account: self.teacher.phone,
          classId: classId.value,
          name: self.teacher.name,
          role: 0,
          type: 0,
        })
        message.success('退出班级成功')
      }
      await deleteTeacherFromClass({
        cid: classId.value,
        teacher: {
          name: teacher.name,
          phone: teacher.phone,
        },
      })

      teachers.value = teachers.value.filter(t => t.phone !== teacher.phone)
      message.success('教师移除成功')
    }
    catch (error) {
      console.error('移除教师失败:', error)
      message.error('移除教师失败')
    }
  }

  function cancelAddTeacher() {
    isAddingTeacher.value = false
    newTeacher.value = { name: '', phone: '' }
  }

  return {
    newTeacher,
    isAddingTeacher,
    handleAddTeacher,
    handleRemoveTeacher,
    cancelAddTeacher,
  }
}
